package cn.mcsys.viewer.core.utils;

import cn.mcsys.myadmin.common.utils.HttpRequestUtil;
import cn.mcsys.viewer.core.utils.conf.WechatConfig;
import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class WechatUtil {

    public static final String OAUTH2_AUTHORIZE = "https://open.weixin.qq.com/connect/oauth2/authorize";
    public static final String OAUTH2_ACCESS_TOKEN = "https://api.weixin.qq.com/sns/oauth2/access_token";
    public static final String SNS_USERINFO = "https://api.weixin.qq.com/sns/userinfo";

    private WechatUtil(){}

    /**
     * 通过code来获取网页token
     * @param code
     * @return
     */
    public static String getWechatUserinfo(String code,String state) throws Exception {
        Map<String, Object> wechatInfo = getWechatInfo(state);
        String result = HttpRequestUtil.httpGet(OAUTH2_ACCESS_TOKEN + "?appid="+ wechatInfo.get("appid") +"&secret="+ wechatInfo.get("secret") +"&code="+ code +"&grant_type=authorization_code",null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return pullUserinfo(jsonObject);
    }

    /**
     * 使用网页token拉取用户基本信息
     * @param jsonObject
     * @return
     */
    private static String pullUserinfo(JSONObject jsonObject) throws Exception {
        String web_access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        Map<String,Object> map = new HashMap<>();
        map.put("access_token",web_access_token);
        map.put("openid",openid);
        map.put("lang","zh_CN");
        return HttpRequestUtil.httpGet(SNS_USERINFO ,map);
    }

    private static Map<String,Object> getWechatInfo(String state){
        HashMap<String, Object> map = new HashMap<>();
        String appid = WechatConfig.getAppid();
        String secret = WechatConfig.getAppsecret();
        map.put("appid",appid);
        map.put("secret",secret);
        return map;
    }
}
